<template>
  <view class="app-container">
    <!-- 自适应导航栏 -->
    <AdaptiveNavBar 
      title="业务选择"
      text-color="#ffffff"
	  :showHome="true"
    />
    
    <view class="content-area" :style="{ marginTop: $navbarUtil.getNavbarTotalHeightRpx() }">
      <view class="main-card">
        <view class="card-header">
          <text class="prompt-text">请选择您要创建的服务商品类别</text>
        </view>

        <view class="business-item" @click="createProduct('yanxue')">
          <view class="icon-wrapper bg-orange">
            <image src="/static/logo.png" class="logo-icon" mode="aspectFit"></image>
          </view>
          <view class="text-content">
            <text class="title">{{ firstOptionTitle }}</text>
            <text class="description">{{ firstOptionDescription }}</text>
          </view>
        </view>
			
        <view v-if="showSecondOption" class="divider"></view>

        <view v-if="showSecondOption" class="business-item" :class="{ 'disabled': businessType === 1 }" @click="handleSecondOption">
          <view class="icon-wrapper bg-orange">
            <image src="/static/logo.png" class="logo-icon" mode="aspectFit"></image>
          </view>
          <view class="text-content">
            <text class="title">{{ secondOptionTitle }}</text>
            <text class="description">{{ secondOptionDescription }}</text>
			<view v-if="businessType === 1" class="overlay"></view>
          </view>
        </view>

        <view v-if="showThirdOption" class="divider"></view>

        <view v-if="showThirdOption" class="business-item" :class="{ 'disabled': businessType === 1 }" @click="handleThirdOption">
          <view class="icon-wrapper bg-orange">
            <image src="/static/logo.png" class="logo-icon" mode="aspectFit"></image>
          </view>
          <view class="text-content">
            <text class="title">{{ thirdOptionTitle }}</text>
            <text class="description">{{ thirdOptionDescription }}</text>
			<view v-if="businessType === 1" class="overlay"></view>
          </view>
        </view>

        <view class="card-footer">
          <view class="more-categories" @click="viewMoreCategories">
            <text>查看更多类别</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
	data() {
		return {
			businessType: 1 // 默认为1
		};
	},
	computed: {
		// 获取导航栏总高度
		navbarTotalHeight() {
			return (getNavbarTotalHeightRpx())
		},
		firstOptionTitle() {
			if (this.businessType === 2) return '目的地接待';
			if (this.businessType === 3) return '创建研学活动';
			return '泛营地接待';
		},
		firstOptionDescription() {
			if (this.businessType === 2) return '创建目的地接待业务服务组合,以此在平台与其他商业/教育伙伴开展经营协作';
			if (this.businessType === 3) return '引用旅行社【研学产品】，提供随队服务，开展研学、冬夏令营、周末营、户外课等活动';
			return '创建营地型研学旅行接待服务组合,以此在平台与其他商业/教育伙伴开展经营协作';
		},
		secondOptionTitle() {
			if (this.businessType === 2) return '组团业务';
			if (this.businessType === 3) return '创建课程（未开放）';
			return '团票业务（功能暂未开放）';
		},
		secondOptionDescription() {
			if (this.businessType === 2) return '调用一类商家的研学接待服务，组合成组团业务，供第三方商业/教育伙伴调用并经营';
			if (this.businessType === 3) return '创建试听课或正价课';
			return '创建团队门票业务,以此在平台供第三方商业/教育伙伴调用并经营的服务组合';
		},
		thirdOptionTitle() {
			if (this.businessType === 2) return '综合研学业务';
			if (this.businessType === 3) return '创建服务（功能未开放）';
			return '门票零售/预订（功能暂未开放）';
		},
		thirdOptionDescription() {
			if (this.businessType === 2) return '创建综合研学服务组合,提供多样化的研学内容';
			if (this.businessType === 3) return '午托、晚托、周托、自习等其他服务';
			return '创建供个人或第三方商家购买/预订/调用的门票';
		},
		// 根据商家类型判断第二、三选项是否显示
		showSecondOption() {
			// B3 只显示一个选项，不显示第二、三个选项
			return this.businessType !== 3;
		},
		showThirdOption() {
			// B3 只显示一个选项，不显示第二、三个选项
			return this.businessType !== 3;
		}
	},
	onLoad() {
		console.log('businessSelection页面加载');
		// 从缓存中获取companyInfo
		try {
			const companyInfo = uni.getStorageSync('companyInfo');
			if (companyInfo && companyInfo.businessType) {
				const bt = Number(companyInfo.businessType);
				this.businessType = Number.isNaN(bt) ? companyInfo.businessType : bt;
				console.log('获取到businessType:', this.businessType);
			}
		} catch (e) {
			console.error('读取companyInfo失败:', e);
		}
		
		// 根据businessType设置导航栏背景色
		if (this.businessType === 2) {
			uni.setNavigationBarColor({
				frontColor: '#ffffff', // 前景色（文字颜色）
				backgroundColor: '#39B54A', // 背景色
				animation: {
					duration: 400,
					timingFunc: 'easeIn'
				}
			});
		}
	},
	methods: {		
		createProduct(type) {
		console.log('创建产品类型:', type);
		
		// 如果是businessType=1，点击"泛营地接待"（第一个选项），直接进入create页面
		if (this.businessType === 1 && type === 'yanxue') {
			// 先保存入口标识到缓存（用于后续草稿检查）
			const businessEntry = 'yanxue';
			const productType = '1' // 泛营地接待
			const jumpUrl = `/public/create/index?type=${type}&productType=${productType}`;
			uni.setStorageSync('businessEntry', businessEntry);
			uni.setStorageSync('productType', productType);
			console.log('productType', productType);
			
			// 检查是否有该入口的草稿
			this.checkAndHandleDraft(businessEntry, () => {
				uni.redirectTo({
					url: jumpUrl
				});
			}, jumpUrl);
			return;
		}
		
	// 如果是businessType=2且是第一个选项（目的地接待业务）
	if (this.businessType === 2 && type === 'yanxue') {
		// 保存入口标识到缓存
		const businessEntry = 'dest_receive';
		const productType = '3' // 目的地接待
		const jumpUrl = `/public/create/index?type=${type}&productType=${productType}`;
		uni.setStorageSync('businessEntry', businessEntry);
		uni.setStorageSync('productType', productType);
		console.log('productType', productType);
		// 检查是否有该入口的草稿，无草稿时直接跳转到创建页
		this.checkAndHandleDraft(businessEntry, () => {
			uni.navigateTo({ url: jumpUrl });
		}, jumpUrl);
		return;
	}

		// 如果是businessType=3且是第一个选项（创建研学活动）
		if (this.businessType === 3 && type === 'yanxue') {
			const businessEntry = 'third_research';
			const productType = '5' // 研学活动	
			const normalJumpUrl = '/pages/merchant/category/index';
			const draftJumpUrl = `/public/create/index?type=${type}&productType=${productType}`;
			uni.setStorageSync('businessEntry', businessEntry);
			uni.setStorageSync('productType', productType);
			console.log('productType', productType);
			this.checkAndHandleDraft(businessEntry, () => {
				// 无草稿：进入分类页
				uni.navigateTo({ url: normalJumpUrl });
			}, draftJumpUrl);
			return;
		}
		
		// 其他情况跳转到原有的创建页面
		uni.navigateTo({
			url: `/public/create/index?type=${type}`
		});
	},
	
	// 检查并处理草稿
	checkAndHandleDraft(businessEntry, onNoDraft, jumpUrl) {
		try {
			console.log('businessEntry',businessEntry)
			const draftList = uni.getStorageSync('productDraftList') || [];
			const matchedDraft = draftList.find(draft => draft.businessEntry === businessEntry);
			
			console.log('检查草稿:', {
				businessEntry,
				draftList,
				matchedDraft,
				jumpUrl
			});
			
			if (matchedDraft) {
				// 找到匹配的草稿，询问用户
				uni.showModal({
					title: '提示',
					content: '检测到该业务入口的未完成草稿，是否使用草稿内容？',
					confirmText: '使用草稿',
					cancelText: '重新开始',
					success: (res) => {
						if (res.confirm) {
							// 使用草稿，跳转到创建页面，添加useDraft参数
							const urlWithDraft = jumpUrl.includes('?') ? `${jumpUrl}&useDraft=true` : `${jumpUrl}?useDraft=true`;
							console.log('跳转到带草稿的URL:', urlWithDraft);
							uni.navigateTo({
								url: urlWithDraft
							});
						} else {
							// 不使用草稿，清空草稿箱
							const updatedDraftList = draftList.filter(draft => draft.businessEntry !== businessEntry);
							uni.setStorageSync('productDraftList', updatedDraftList);
							console.log('用户选择不使用草稿，已清空该入口的草稿');
							
							// 继续正常跳转
							if (onNoDraft) {
								onNoDraft();
							}
						}
					}
				});
			} else {
				// 没有草稿，正常跳转
				if (onNoDraft) {
					onNoDraft();
				}
			}
		} catch (error) {
			console.error('检查草稿失败:', error);
			// 出错时也正常跳转
			if (onNoDraft) {
				onNoDraft();
			}
		}
	},
		showComingSoon() {
			uni.showToast({
				title: '该功能开发中',
				icon: 'none',
				duration: 2000
			});
		},
		viewMoreCategories() {
			uni.showToast({
				title: '查看更多类别功能待开发',
				icon: 'none'
			});
		},
			handleSecondOption() {
		if (this.businessType === 2) {
			// B2商家点击"组团业务" - 需要调用B1的产品
			// 保存入口标识到缓存
			const businessEntry = 'group_travel';
			const productType = '4'; // 组团业务
			const normalJumpUrl = '/pages/merchant/category/index';
			const draftJumpUrl = `/public/create/index?type=group_travel&productType=${productType}`;
			uni.setStorageSync('businessEntry', businessEntry);
			uni.setStorageSync('productType', productType);
			console.log('B2商家选择组团业务, productType:', productType);
			
			// 检查是否有该入口的草稿
			this.checkAndHandleDraft(businessEntry, () => {
				// 没有草稿时跳转到分类页面，可以选择要调用的B1产品
				uni.navigateTo({
					url: normalJumpUrl
				});
			}, draftJumpUrl);
		} else {
			// B1商家的团票业务暂未开放
			uni.showToast({
				title: '该功能暂未开放',
				icon: 'none',
				duration: 2000
			});
		}
	},
	handleThirdOption() {
		if (this.businessType === 2) {
			// B2商家点击"综合研学业务" - 直接创建
			// 保存入口标识到缓存
			const businessEntry = 'comprehensive_study';
			const productType = '2'; // 综合研学业务
			const jumpUrl = `/public/create/index?type=comprehensive_study&productType=${productType}`;
			uni.setStorageSync('businessEntry', businessEntry);
			uni.setStorageSync('productType', productType);
			console.log('B2商家选择综合研学业务, productType:', productType);
			
			// 检查是否有该入口的草稿
			this.checkAndHandleDraft(businessEntry, () => {
				// 直接跳转到创建页面
				uni.navigateTo({
					url: jumpUrl
				});
			}, jumpUrl);
		} else {
			// B1商家的门票零售/预订暂未开放
			uni.showToast({
				title: '该功能暂未开放',
				icon: 'none',
				duration: 2000
			});
		}
	}
	},
};
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.content-area {
  flex: 1;
  padding: 30rpx 20rpx;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.main-card {
  background-color: #ffffff;
  border-radius: 20rpx;
  width: 100%;
  max-width: 690rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.card-header {
	display: flex;
	align-items: center;
	justify-content: center;
  padding: 20rpx 30rpx 20rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.prompt-text {
  font-size: 28rpx;
  color: #666666;
  text-align: center;
  line-height: 1.5;
}

.business-item {
  padding: 30rpx;
  display: flex;
  align-items: flex-start;
  transition: background-color 0.2s ease;
  // position: relative;

  &:active {
    background-color: #f8f8f8;
  }

  &.disabled {
    .title {
      // color: #999999;
    }

    .description {
      // color: #cccccc;
    }
  }
}

.icon-wrapper {
  width: 120rpx;
  height: 120rpx;
  // border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 30rpx;
  flex-shrink: 0;

  &.bg-orange {
    background: linear-gradient(135deg, #ff9500, #ffcc00);
  }
}

.logo-icon {
  width: 100%;
  height: 100%;
}

.text-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  position:relative;
  height: 120rpx;
  justify-content: flex-start;
}

.title {
  font-size: 28rpx;
  font-weight: bold;
  color: #666666;
  line-height: 1.2;
  margin-bottom: 10rpx;
  z-index: 2;
}

.description {
  font-size: 24rpx;
  color: #a0a0a0;
  line-height: 1.4;
  word-break: break-word;
  z-index: 2;
}

.divider {
  height: 1rpx;
  background-color: #f0f0f0;
  margin: 0 30rpx;
}

.card-footer {
  padding: 30rpx;
  border-top: 1rpx solid #f0f0f0;
}

.more-categories {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  font-size: 28rpx;
  color: #6A7FA5;
}

.more-categories text {
  margin-right: 10rpx;
}

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #f2f2f2;
  border-radius: 0;
  z-index: 1;
}
</style>